package com.android.tripspins.app.services;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.IBinder;
import android.preference.PreferenceManager;

import com.android.tripspins.app.bo.Attachment;
import com.android.tripspins.app.bo.Pin;
import com.android.tripspins.app.bo.Trip;
import com.android.tripspins.app.bo.User;
import com.android.tripspins.app.dao.TripDAO;
import com.android.tripspins.app.dao.UserDAO;
import com.android.tripspins.app.helper.DbHelper;
import com.android.tripspins.app.helper.SyncHelper;

import java.io.File;

/**
 * Created by João.Rutkoski on 09/04/14.
 */
public class BackgroundSyncService extends Service {

    SharedPreferences settings;
    IBinder mBinder;
    DbHelper dbHelper;
    SQLiteDatabase database ;
    TripDAO tripDAO;


    public BackgroundSyncService ()
    {

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {


        settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        dbHelper = new DbHelper(getApplicationContext());

        boolean syncOnlyOnWiFi = settings.getBoolean("pref_key_sync_wifi",true);
        boolean syncNow = false;
        ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo infoWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        boolean networkConnected = connManager.getActiveNetworkInfo().isConnected();
        if(syncOnlyOnWiFi)
        {
            if (infoWifi.isConnected()) {
                syncNow = true;
            }

        }
        else
        {
            if(networkConnected || infoWifi.isConnected())
            {
                syncNow = true;
            }
        }


        if(syncNow) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        database = dbHelper.getReadableDatabase();
                        tripDAO = new TripDAO(database);
                        UserDAO userDAO = new UserDAO(database);
                        User authenticatedUser = userDAO.getLoggedUser();
                        if(authenticatedUser != null) {
                            for (Trip trip : tripDAO.getTripsToSync(authenticatedUser.getId())) {
                                SyncHelper syncHelper = new SyncHelper();
                                syncHelper.sync(trip, getApplicationContext(), authenticatedUser.getIdOnServer());
                            }

                            for (Trip trip : tripDAO.getTripsSynced(authenticatedUser.getId())) {
                                SyncHelper syncHelper = new SyncHelper();
                                for (Pin pin : trip.getPins()) {
                                    for (Attachment attachment : pin.getAttachments()) {
                                        File toSync = new File(attachment.getPath());
                                        if (toSync.exists()) {
                                            syncHelper.sync(trip.getIdOnServer()
                                                    , pin.getId()
                                                    , attachment.getId()
                                                    , toSync
                                                    , getApplicationContext()
                                            );
                                        }
                                    }
                                }

                            }
                        }
                        database.close();

                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
            }).start();
        }
        return super.onStartCommand(intent, flags, startId);


    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

}
